﻿using System;

using System.Linq;
using System.Web.Mvc;

using PagedList;
using AutoMapper;


using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.ViewModel;
using SIG.Infrastructure.Extensions;
using SIG.Resources.Admin;
using SIG.Infrastructure.Helper;
using System.Xml.Linq;
using SIG.Service.LuceneSearch;
using SIG.Model.LuceneSearch;
using SIG.DAL.Dapper.Repositories;
using SIG.DAL.Dapper.Model;
using SIG.ViewModel.Admin.Case;
using SIG.InputModel.Admin.Case;
using System.Web.Hosting;
using System.Web;
using System.IO;

namespace SIG.WebMVC.Areas.Admin.Controllers
{

    [SIGAuth]
    public class WorkController : BaseController
    {
      
         private readonly WorkCategoryRepository _categoryRepository;
         private readonly WorkRepository _workRepository;
      //   private readonly WorkPhotoRepository _workPhotoRepository;
        private readonly PageMetaRepository _pageMetaRepository;
        private readonly IMapper _mapper;

        public WorkController(IMapper mapper)
        {
            _categoryRepository = new WorkCategoryRepository();
            _workRepository = new WorkRepository();
         //   _workPhotoRepository = productPhotoService;
            _pageMetaRepository = new PageMetaRepository();
            _mapper = mapper;

        }
        

        #region  案例

        [HttpGet]
         public ActionResult Index(int? page, int? categoryId, string keyword)
         {
            var vm = new WorkListVM()
            {
                CategoryId = categoryId ?? 0,
                PageIndex = (page ?? 1),
                PageSize = SettingsManager.Case.PageSize,
                Keyword = keyword
            };
            int totalCount = 0;
            var list = _workRepository.GetListPagedItems(vm.PageIndex, vm.PageSize,  (int)vm.CategoryId, vm.Keyword, out totalCount);
          
             vm.TotalCount = totalCount;

            var categoryList = _categoryRepository.GetItems().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;
            
            foreach(var item in list)
            {
                item.Categories = _categoryRepository.GetItemsByWorkId(item.Id);
            }

            vm.Works = new StaticPagedList<Work>(list, vm.PageIndex, vm.PageSize, vm.TotalCount);
            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(vm);
         }

        

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/WorkSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        public ActionResult Add()
         {
            WorkIM product = new WorkIM()
            {
                Active = true
            };
            var categoryList = _categoryRepository.GetActiveItems().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            return View(product);
         }


         [HttpPost]
         [ValidateAntiForgeryToken]
         public JsonResult Add(WorkIM vm)
         {           

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var newWork = _mapper.Map<WorkIM, Work>(vm);
                newWork.ViewCount = 0;
                newWork.CreatedDate = DateTime.Now;
                newWork.CreatedBy = Site.CurrentUserName;

                var lCategories = (from c in _categoryRepository.GetItems()
                                   where vm.CategoryIds.Contains(c.Id.ToString())
                                   select c).ToList();
                            

                _workRepository.Create(newWork, lCategories);

                var pageMeta = new PageMeta()
                {
                    ObjectId = newWork.Id.ToString(),
                    Title = string.IsNullOrEmpty(vm.SEOTitle) ? $"{vm.Title}" : vm.SEOTitle,
                    Keyword = string.IsNullOrEmpty(vm.Keywords) ? vm.Title : vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = (short)ModelType.PRODUCT
                };
                _pageMetaRepository.Create(pageMeta);
                

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Work));              
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }



        }

        [HttpGet]
        public ActionResult Edit(int id)
        {

            var vWork = _workRepository.GetById(id);
            var categories = _categoryRepository.GetItemsByWorkId(id);

            if (vWork == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }
            
            var editWork = _mapper.Map<Work, WorkIM>(vWork);

            if (categories.Any())
                editWork.CategoryIds = categories.Select(c => c.Id.ToString()).ToArray();

            var pageMeta = _pageMetaRepository.GetPageMeta(ModelType.PRODUCT, editWork.Id.ToString());
            if (pageMeta != null)
            {
                editWork.Title = pageMeta.Title;
                editWork.Keywords = pageMeta.Keyword;
                editWork.SEODescription = pageMeta.Description;
            }

            var categoryList = _categoryRepository.GetActiveItems().OrderByDescending(c => c.Importance).ToList();
            var lCategories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = lCategories;

            //ViewBag.Categories = GetWorkCategoryList();
            return View(editWork);


        }


        
         [HttpPost]
      
         [ValidateAntiForgeryToken]
         public JsonResult Edit(WorkIM vm)
         {
            
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            

            try
            {
                var editWork = _workRepository.GetById(vm.Id);
                editWork.Title = vm.Title;
               
                editWork.Thumbnail = vm.Thumbnail;
                editWork.Recommend = vm.Recommend;
                editWork.Active = vm.Active;
                editWork.Body = vm.Body;
                editWork.ImageUrl = vm.ImageUrl;
                editWork.Abstract = vm.Abstract;
                // editWork.ImageUrl = vm.I
               
                editWork.UpdatedBy = Site.CurrentUserName;
                editWork.UpdatedDate = DateTime.Now;

                var lCategories = (from c in _categoryRepository.GetItems()
                                   where vm.CategoryIds.Contains(c.Id.ToString())
                                   select c).ToList();

                //var editWork = _mapper.Map<WorkIM, Work>(product);
                //product.WorkCategoryIds = string.Join(",", product.PostWorkCategoryIds);

                _workRepository.Update(editWork, lCategories);

                var pageMeta = _pageMetaRepository.GetPageMeta(ModelType.PRODUCT, editWork.Id.ToString());
                pageMeta = pageMeta ?? new PageMeta();
                

                pageMeta.ObjectId = editWork.Id.ToString();
                pageMeta.Title = string.IsNullOrEmpty(vm.Title) ? vm.Title : vm.Title;
                pageMeta.Keyword = string.IsNullOrEmpty(vm.Keywords) ? vm.Title : vm.Keywords.Replace('，', ',');
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = (short)ModelType.PRODUCT;
                 
                if(pageMeta.Id >0 )
                {
                    _pageMetaRepository.Update(pageMeta);
                }                       
                else
                {                    
                    _pageMetaRepository.Create(pageMeta);
                }                

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
                        

         }

         [HttpPost]
         public JsonResult Recommend(int id)
         {

             Work vWork = _workRepository.GetById(id);

            if (vWork == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
             {
                
                vWork.Recommend = !vWork.Recommend;
                _workRepository.Update(vWork);

             //   var vm = _mapper.Map<WorkVM>(vWork);
                AR.Data = RenderPartialViewToString("_WorkItem", vWork);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
             catch (Exception ex)
             {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
         
         }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Work vWork = _workRepository.GetById(id);

            try
            {
                vWork.Active = !vWork.Active;
                _workRepository.Update(vWork);

             //   var vm = _mapper.Map<WorkVM>(vWork);
                AR.Data = RenderPartialViewToString("_WorkItem", vWork); 

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }



         [HttpPost]
         [ValidateAntiForgeryToken]
         public JsonResult Delete(int id)
         {

            // Work vWork = _workRepository.GetById(id);

            //if (vWork == null)
            //{
            //    AR.Setfailure(Messages.HttpNotFound);
            //    return Json(AR, JsonRequestBehavior.DenyGet);
            //}
                      
            _workRepository.Delete(id);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Technology));
            return Json(AR, JsonRequestBehavior.DenyGet);         

           
         }

        /// <summary>
        /// 创建索引目录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CreateIndex()
        {
            try
            {
                var list = _workRepository.GetActiveItems().Select(m => new SearchData
                {
                    Id = $"PRODUCT{m.Id}",
                    Name = m.Title,
                    Description = m.Body,
                    ImageUrl = m.Thumbnail,
                    Url = $"{SettingsManager.Site.SiteDomainName}/work/detail/{m.Id}"
                }).ToList();

                GoLucene.AddUpdateLuceneIndex(list);

                AR.SetSuccess(String.Format(Messages.AlertActionSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }




        [HttpPost]
        public ActionResult UpLoadImages(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePathName = string.Empty;

            string dir = "/Uploads/Images/Works";
            string localPath = HostingEnvironment.MapPath(dir);
            // string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Uploads");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }

            string ex = Path.GetExtension(file.FileName);
            filePathName = Guid.NewGuid().ToString("N") + ex;
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }


            var orgUrl = Path.Combine(localPath, filePathName);
            file.SaveAs(orgUrl);


            return Json(new
            {
                jsonrpc = "2.0",
                id = id,
                fileName = dir + "/" + filePathName
            });

        }
        [HttpPost]
        public ActionResult RemoveImage(string img)
        {
            try
            {
                string dir = "/Uploads/Images/Works";
                string localPath = HostingEnvironment.MapPath(dir);
                var orgUrl = Path.Combine(localPath, img);


                if (System.IO.File.Exists(orgUrl))
                {
                    System.IO.File.Delete(orgUrl);
                }

                AR.SetSuccess(Messages.AlertActionSuccess);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }



        #endregion

   
    }
}
